package com.jch.har.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class NettyServer {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SSS");

    public static void main(String[] args) {
        new NettyServer().bind(1131);
    }

    private void bind(int port) {
        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup();

        ServerBootstrap b = new ServerBootstrap()
                .group(worker, worker)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {

                        /**
                         * 心跳检测
                         * readerIdleTimeSeconds 读超时时间
                         * writeIdleTimeSeconds 写超时时间
                         * allIdleTimeSeconds 读写超时时间
                         * TimeUnit.SECONDS 单位：秒
                         */
                        ch.pipeline().addLast(new IdleStateHandler(2, 2, 2, TimeUnit.SECONDS));
                        // 基于换行符 \r\n
                        ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                        ch.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
                        ch.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));

                        ch.pipeline().addLast(new ServerHandler());
                    }
                });

        try {
            ChannelFuture channelFuture = b.bind(port).sync();
            System.out.println(dateFormat.format(new Date()) + " netty server start done.");
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            System.err.println(dateFormat.format(new Date()) + " 异常：" + e.getMessage());
        } finally {
            worker.shutdownGracefully();
            boss.shutdownGracefully();
            System.out.println(dateFormat.format(new Date()) + " netty server stop done.");
        }
    }
}
